package com.kchouse.homepage;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.kchouse.Alipay.Alipayapi;
import com.kchouse.Alipay.AuthResult;
import com.kchouse.Alipay.OrderInfoUtil2_0;
import com.kchouse.Alipay.PayResult;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.CashCouponItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.BaseApp;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.Map;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

import static com.kchouse.Alipay.Alipayapi.SDK_AUTH_FLAG;
import static com.kchouse.Alipay.Alipayapi.SDK_PAY_FLAG;

public class BuyPrestoreOrderActivity extends BaseActivity implements View.OnClickListener {

    private BuyPrestoreOrderActivity mContent;
    private Intent intent;
    private int buynum;
    private JSONObject prestorejson;
    private TextView tv_title;
    private ImageView iv_back;
    private TextView tv_original;
    private TextView tv_goodtitle;
    private TextView tv_price;
    private TextView tv_buynum;
    private TextView pay_money;
    private int cashNum;
    private int mingcashcouponnum;
    private TextView tv_mingcashcouponnum;
    private double paymoney;//实际付款
    private int usecoup;//使用现金券数量
    private TextView tv_couponlimit;
    private Button bt_pay;
    public static String orderNo;
    boolean isweixin = true;//默认微信支付

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        setContentView(R.layout.activity_buy_prestore_order);

        mContent = this;
        addAct(mContent);
        intiView();
        intiData();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("确认订单");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        tv_original = (TextView) findViewById(R.id.tv_original);
        tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
        tv_goodtitle = (TextView) findViewById(R.id.tv_goodtitle);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_buynum = (TextView) findViewById(R.id.tv_buynum);
        pay_money = (TextView) findViewById(R.id.pay_money);
        tv_mingcashcouponnum = (TextView) findViewById(R.id.tv_mingcashcouponnum);
        tv_couponlimit = (TextView) findViewById(R.id.tv_couponlimit);
        bt_pay = (Button) findViewById(R.id.bt_pay);
        bt_pay.setOnClickListener(this);
    }


    private void intiData() {

        intent = getIntent();
        buynum = intent.getIntExtra("buynum", 1);
        cashNum = intent.getIntExtra("cashNum", 1);
        String prestorestr = intent.getStringExtra("prestorestr");
        prestorejson = JSONObject.parseObject(prestorestr);

        GetMineCashCoupons();


    }

    /**
     * 获取我的现金券
     */
    private void GetMineCashCoupons() {
        String url = API.GetMineCashCoupons + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("token", MineFragment.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    CashCouponItem data = JSONObject.parseObject(datastr, CashCouponItem.class);
                    mingcashcouponnum = Integer.valueOf(data.getNum());
                    tv_mingcashcouponnum.setText("现有可用现金券：" + (data.getNum() * 10) + "元");

                    intigooddata(prestorejson);
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 初始化数据
     *
     * @param json
     */
    private void intigooddata(JSONObject json) {
        tv_buynum.setText("" + buynum);
        tv_goodtitle.setText(json.getString("title"));
//        tv_original.setText(MyUtils.getdouble(json.getDouble("originalPrice")));
        tv_original.setText(json.getDouble("originalPrice") + "");
//        tv_price.setText(MyUtils.getdouble(json.getDouble("price")));
        tv_price.setText(json.getDouble("price") + "");
//        pay_money.setText(MyUtils.getdouble((json.getDouble("price")*buynum)) + "元");

        cashNum = cashNum * buynum;
        if (mingcashcouponnum >= cashNum) {
            tv_couponlimit.setText("本次可抵扣：" + (cashNum * 10) + "元");
            double deductmoney = cashNum * 10;
            Double price = Double.valueOf(prestorejson.getString("price"));

            pay_money.setText(MyUtils.getdouble((price * buynum - deductmoney)) + "元");
            usecoup = cashNum;
            paymoney = price * buynum - deductmoney;

        } else {
            tv_couponlimit.setText("当前可用现金券：" + mingcashcouponnum * 10 + "元");
            double deductmoney = mingcashcouponnum * 10;
            Double price = Double.valueOf(prestorejson.getString("price"));
            pay_money.setText(MyUtils.getdouble((price * buynum - deductmoney)) + "元");
            usecoup = mingcashcouponnum;
            paymoney = price * buynum - deductmoney;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                delAct(mContent);
                finish();
                break;
            case R.id.bt_pay:
//                WXPayReq wxPayReq = new WXPayReq();
//                wxPayReq.setUser_id(User_id);
//                wxPayReq.setChannel_id(Channel_id);
//                wxPayReq.setGoods_id(goodsID);

                if (paymoney < 0) {
                    ToastUtils.getInstanc(mContent).showToast("非法金额，请联系客服");
                } else {
                    Payshowdialog();
                }
                break;
        }
    }

    public void Payshowdialog() {
        isweixin = true;
        final String items[] = {"微信支付", "支付宝支付"};
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setIcon(R.mipmap.icon)//设置标题的图片
                .setTitle("支付类型")//设置对话框的标题
                .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        ToastUtils.getInstanc(mContent).showToast(items[which]);
                        if (items[which].equals("微信支付")) {
                            isweixin = true;
                        } else {
                            isweixin = false;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        createOrder(isweixin);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    //支付宝支付结果回调
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            Log.e("====",msg.toString());
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
//                        ToastUtils.getInstanc(mContent).showToast("支付成功");
                        ToastUtils.getInstanc(mContent).showToast("支付成功");
                        intent.putExtra("Order","2");//预存订单
                        intent.setClass(mContent, PayResultsActivity.class);
                        startActivity(intent);
                        BuyPrestoreOrderActivity.orderNo="";
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
//                        ToastUtils.getInstanc(mContent).showToast("支付失败");
//                        ToastUtils.getInstanc(mContent).showToast(payResult.toString());
                        Log.e("====",payResult.toString());
                        ToastUtils.getInstanc(mContent).showToast("支付失败");
                        PostCancelOrder();
                    }
                    break;
                }
            }
        }

        ;
    };


    /**
     * 取消订单
     */
    private void PostCancelOrder() {
        String url = API.PostCancelOrder + BuyPrestoreOrderActivity.orderNo;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("orderId", BuyPrestoreOrderActivity.orderNo);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
//                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
//                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
//                dismissdialog();
            }

        });
    }

    //支付页面
    private void showalipay(String sign) {
//        boolean rsa2 = (Alipayapi.RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(Alipayapi.APPID, rsa2);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//
//        String privateKey = rsa2 ? Alipayapi.RSA2_PRIVATE :Alipayapi.RSA_PRIVATE;
//        String sign2 = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);

//        final String orderInfo = orderNo + "&" +sign;
        final String orderInfo = sign;
//        final String orderInfo = orderParam + "&" +sign2;
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mContent);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * 创建订单
     */
    private void createOrder(final boolean isweixin) {
        String url = API.PostCreateOrder;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        JSONObject ob = new JSONObject();
        ob.put("suitId", prestorejson.getString("id"));
        ob.put("userId", MainActivity.userid);
        ob.put("cashNum", usecoup);
        ob.put("suitCount", buynum);
        ob.put("type", prestorejson.getString("type"));
        params.applicationJson(ob);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    orderNo = data.getString("orderNo");

                    if (isweixin) {
                        weixin();
                    } else {
                        alipay();
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }

    /**
     * 支付宝支付
     */
    private void alipay() {
        String url = API.PostaliPay;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("outTradeNo", orderNo);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);

                    showalipay(data.getString("orderStr"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }


    /**
     * 微信支付
     */
    private void weixin() {
        String url = API.PostCreateOrder2 + orderNo;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("suitId", suit.getString("id"));

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    payWeChat(data.getString("appid"), data.getString("partnerid"), data.getString("prepayid"), data.getString("noncestr"), data.getString("timestamp"), data.getString("sign"));
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }

    /**
     * 发起微信支付
     */
    private void payWeChat(String WeChatID, String WeChatpartnerId, String prepayId, String nonceStr, String timeStamp, String sign) {

        if (!BaseApp.msgApi.isWXAppInstalled()) {
            ToastUtils.getInstanc(mContent).showToast("请先安装微信！");
            return;
        }
        PayReq payReq = new PayReq();
        payReq.appId = WeChatID;//应用ID
        payReq.partnerId = WeChatpartnerId;//商户号
        payReq.prepayId = prepayId;//预支付交易会话ID
        payReq.packageValue = "Sign=WXPay";//扩展字段
        payReq.nonceStr = nonceStr;//随机字符串
        payReq.timeStamp = timeStamp;//时间戳
//        payReq.extData= "app data"; // optional
        payReq.sign = sign;//签名
//        BaseApp.msgApi.sendReq(payReq);
        BaseApp.msgApi.sendReq(payReq);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            delAct(mContent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
